package input_output;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;


public class Save extends JComponent{
	
	private String extension;
	private Image saveImage;
	private JFileChooser fc;
	
	//Constructor
	public Save(Image image, String ext){
		extension = ext;
		saveImage = image;
	}
	
	public void saveImage(){
		BufferedImage newImage = toBufferedImage(saveImage);
		//default filename
		String defaultFileName = "noName";
		File file = new File(defaultFileName + "." + extension);
		
		//File chooser
		fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		//setBMP
		FileFilter type = new ExtensionFilter("Image file", "." + extension);
		fc.addChoosableFileFilter(type);
    	fc.setSelectedFile(file);
		int returnVal = fc.showSaveDialog(this);		
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fc.getSelectedFile();
            //Check if overwriting is needed
            if(selectedFile.exists()){
    	        int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?","Existing file",JOptionPane.YES_NO_OPTION);
    	        switch(result){
    	            case JOptionPane.YES_OPTION:
    	            	try {
        	                ImageIO.write(newImage, extension, selectedFile);
	        	         } 
	        	    	 catch(IOException e) {
	        	            	JOptionPane.showMessageDialog(this, "Write error for " + file.getPath() + ": " + e.getMessage(), "Unable to save file", JOptionPane.ERROR_MESSAGE);
	        	         }
    	                break;
    	            case JOptionPane.NO_OPTION:
    	            	//user refused
    	            	//TODO: let user choose another file
    	                break;
    	        }
            }
    	     else{
    	    	 try {
    	                ImageIO.write(newImage, extension, selectedFile);
    	         } 
    	    	 catch(IOException e) {
    	            	JOptionPane.showMessageDialog(this, "Write error for " + file.getPath() + ": " + e.getMessage(), "Unable to save file", JOptionPane.ERROR_MESSAGE);
    	         }
    	     }
        } 
        else {
            //user canceled
        }		
	}
	
	//convert Image to BufferedImage
	private BufferedImage toBufferedImage(Image src) {
        int w = src.getWidth(null);
        int h = src.getHeight(null);
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage dest = new BufferedImage(w, h, type);
        Graphics2D g2 = dest.createGraphics();
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return dest;
    }

}
